package com.github.sbb.sherry.primitives.rules;

import com.github.sbb.sherry.common.annotations.NotNull;
import com.github.sbb.sherry.common.base.Preconditions;
import com.github.sbb.sherry.primitives.api.Facts;
import com.github.sbb.sherry.primitives.api.FactsSupplier;
import com.github.sbb.sherry.primitives.api.RuleListener;
import com.github.sbb.sherry.primitives.api.Rules;
import com.github.sbb.sherry.primitives.api.RulesEngineListener;
import com.github.sbb.sherry.primitives.core.AbstractRulesEngine;
import com.github.sbb.sherry.primitives.exception.FetcherException;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public final class DefaultRulesEngine extends AbstractRulesEngine {

  private static final Logger logger = LoggerFactory.getLogger(DefaultRulesEngine.class);

  public static final DefaultStatelessRulesEngine statelessRulesEngine = new DefaultStatelessRulesEngine();

  @NotNull
  private Rules rules;

  @NotNull
  private FactsSupplier factsSupplier;

  public DefaultRulesEngine(Rules rules) {
    super();
    this.rules = rules;
  }

  public void setFactsSupplier(FactsSupplier factsSupplier) {
    this.factsSupplier = factsSupplier;
  }

  public DefaultRulesEngine(Rules rules, List<RuleListener> ruleListeners,
      List<RulesEngineListener> rulesEngineListeners) {
    super(ruleListeners, rulesEngineListeners);
    this.rules = rules;
  }

  @Override
  public void fire(Map<String, Object> params) {
    Preconditions.checkNotNull(rules, "rules 不能为空");
    Preconditions.checkNotNull(factsSupplier, "factsSupplier 不能为空");
    Facts facts = null;
    try {
      facts = factsSupplier.get(params);
    } catch (FetcherException e) {
      e.printStackTrace();
    }
    statelessRulesEngine.fire(rules, facts, getRuleListeners());
  }
}
